package com.five.service.impl;

import com.five.basic.service.impl.BaseServiceImpl;
import com.five.dto.UpdateDto;
import com.five.exception.BusinessException;
import com.five.mapper.ChapterMapper;
import com.five.pojo.Chapter;
import com.five.pojo.Novel;
import com.five.service.IChapterService;
import com.five.service.INovelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.five.constants.StatusConstant;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class ChapterServiceImpl extends BaseServiceImpl<Chapter> implements IChapterService {

    @Autowired
    private INovelService novelService;

    @Autowired
    private ChapterMapper chapterMapper;

    @Override
    public void createChapter(Chapter chapter) {
//      1.校验
        if (null == chapter) {
            throw new BusinessException("无效章节");
        }
        Long novelId = null;
//        1.1校验novel_id
        if (null == chapter.getNovelId()) {
//          1.1.1新增一条空的小说记录
            Novel novel = novelService.createBlankNovel(chapter.getAuthorId());
//          1.1.2关联章节与小说
            novelId = novel.getId();
            chapter.setNovelId(novelId);
        } else {
//          1.1.3校验小说是否存在
            novelId = chapter.getNovelId();
            if (!novelService.isExist(novelId)) {
                throw new BusinessException("小说不存在");
            }
        }
//          1.2校验章节信息
        validateChapter(chapter);

//       2.章节数据初始化
//          2.1 补充默认字段
        if (null == chapter.getWordCount() || chapter.getWordCount() < 0) {
            chapter.setWordCount(chapter.getContent().length());
        }
        chapter.setCreateTime(LocalDateTime.now());
        chapter.setUpdateTime(LocalDateTime.now());
        chapter.setStatus(StatusConstant.ChapterStatus.CHAPTER_AUDITING);
//       3. 入库
//          3.1 新增章节记录
        chapterMapper.add(chapter);
//          3.2 更新小说信息（审核通过再更新吧）
    }

    @Override
    public void delete(Long chapterId) {
        // 1.校验
        if (null == chapterId || chapterId <= 0) {
            throw new BusinessException("无效章节");
        }
        // 2.获取小说信息
        // 2.删除章节
        chapterMapper.delete(chapterId);
        // 3. 更新小说信息（审核通过再更新吧）
    }


    @Override
    public void update(Chapter chapter) {
//       1.校验
//        1.1 有效性校验
        if (null == chapter) {
            throw new BusinessException("无效章节");
        }
//        1.2获取章节信息
        Long id = chapter.getId();
        Long novelId = chapter.getNovelId();
//        1.3 信息校验
        if (null == id) {
            throw new BusinessException("无效章节");
        }
        if (null == novelId) {
            throw new BusinessException("无效小说");
        }
        validateChapter(chapter);
        // 2.补充默认字段
        if (null == chapter.getWordCount() || chapter.getWordCount() < 0) {
            chapter.setWordCount(chapter.getContent().length());
        }
        chapter.setUpdateTime(LocalDateTime.now());
        chapter.setStatus(StatusConstant.ChapterStatus.CHAPTER_AUDITING);
        chapterMapper.update(chapter);
        // 3. 更新小说信息（审核通过再更新吧）
    }


    @Override
    public List<Chapter> queryChapterList(Long novelId) {
        return chapterMapper.queryChapterList(novelId);
    }


    @Override
    public void batchCreate(List<Chapter> chapters) {
//      1.循环校验章节信息
        for (int i = 0; i < chapters.size(); i++) {
            Chapter chapter = chapters.get(i);
            if (null == chapter) {
                throw new BusinessException("第" + (i + 1) + "个章节无效");
            }
            validateChapter(chapter);
        }
        // 2.补充默认字段
        List<Chapter> list = chapters.stream().peek(chapter -> {
            if (null == chapter.getWordCount() || chapter.getWordCount() < 0) {
                chapter.setWordCount(chapter.getContent().length());
            }
            chapter.setCreateTime(LocalDateTime.now());
            chapter.setUpdateTime(LocalDateTime.now());
            chapter.setStatus(StatusConstant.ChapterStatus.CHAPTER_AUDITING);
        }).collect(Collectors.toList());
        // 3. 入库
        chapterMapper.batchAdd(list);
    }

    @Override
    public void updateStatus(UpdateDto dto) {
        // 1.校验
        if (null == dto) {
            throw new BusinessException("无效的更新参数");
        }
        Long chapterId = dto.getId();
        Byte status = dto.getStatus();
        if (null == chapterId || chapterId <= 0) {
            throw new BusinessException("无效的章节");
        }
        if (null == status || !StatusConstant.isValidChapterStatus(status)) {
            throw new BusinessException("无效的章节状态");
        }
        // 2.更新章节状态
        Chapter chapter = chapterMapper.queryById(chapterId);
        if (null == chapter) {
            throw new BusinessException("章节不存在");
        }
        chapter.setUpdateTime(LocalDateTime.now());
        chapterMapper.updateStatus(chapterId, status);
    }

    /**
     * 章节信息校验
     *
     * @param chapter 章节信息
     */
    private void validateChapter(Chapter chapter) {
//        1.2章节序号校验
//        1.2.1 有效性校验
        if (null == chapter.getSort() || chapter.getSort() < 0) {
            throw new BusinessException("无效的章节序号");
        }
//        1.2.2 重复性校验
        if (isDuplicateSort(chapter.getNovelId(), chapter.getSort(), chapter.getId())) {
            throw new BusinessException("章节序号重复");
        }
//        1.3校验标题
//        1.3.1 有效性校验
        if (null == chapter.getTitle() || StringUtils.isBlank(chapter.getTitle())) {
            throw new BusinessException("无效的章节标题");
        }
//        1.3.2 长度校验
        String title = chapter.getTitle();
        if (title.length() < 5) {
            throw new BusinessException("章节标题长度不能少于5个字符");
        }
        if (title.length() > 20) {
            throw new BusinessException("章节标题长度不能超过20个字符");
        }
//        1.4校验内容
//        1.4.1 有效性校验
        if (null == chapter.getContent() || StringUtils.isBlank(chapter.getContent())) {
            throw new BusinessException("无效的章节内容");
        }
        String content = chapter.getContent();
        if (content.length() < 1000) {
            throw new BusinessException("内容不得少于1000字");
        }
    }


    /**
     * 校验章节序号是否重复
     *
     * @param novelId   小说id
     * @param sort      章节序号
     * @param chapterId 章节id
     * @return true:重复 false:不重复
     */
    public boolean isDuplicateSort(Long novelId, Integer sort, Long chapterId) {
        //根据序号和小说id查章节
        Chapter chapter = chapterMapper.queryBySortAndNovelId(novelId, sort);
        if (null == chapter) {
            return false;
        }
        return !chapter.getId().equals(chapterId);
    }


}
